package com.novunda.platform.web.advice;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author linfeng
 * @since 2016/9/22.
 */
//@Component
//@ControllerAdvice(basePackages = "com.novunda.platform.web")
public class GlobalExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 未登录异常处理
     * @param ex UnauthenticatedException
     * @return 页面
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthenticatedException.class)
    public String unauthenticated(UnauthenticatedException ex) {
        LOG.info("UnauthenticatedException {}", ex.getMessage(), ex);
        return "redirect:/login";
    }

    /**
     * 未授权异常处理
     * @param ex UnauthorizedException
     * @return 页面
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public String unauthorized(UnauthorizedException ex) {
        LOG.info("UnauthorizedException {}", ex.getMessage(), ex);
        return "redirect:/unauthorized";
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ModelAndView handSql(Exception ex) {
        LOG.info("SQL Exception {}", ex.getMessage(), ex);
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", ex.getMessage());
        mv.setViewName("errors/500");
        return mv;
    }

}
